package com.sdkj.fixed.asset.login.service;



import cn.hutool.core.util.StrUtil;
import com.sdkj.fixed.asset.api.login.out_vo.CompanyBaseListResult;
import com.sdkj.fixed.asset.api.login.out_vo.MenuResultEntity;
import com.sdkj.fixed.asset.api.login.pojo.LoginRole;
import com.sdkj.fixed.asset.api.system.out_vo.DictionaryResult;
import com.sdkj.fixed.asset.api.system.out_vo.UsageResult;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.login.mapper.LoginMapper;
import com.sdkj.fixed.asset.login.util.CacheUtil;
import com.sdkj.fixed.asset.login.util.RedisUtil;
import com.sdkj.fixed.asset.login.util.RoleType;

import com.sdkj.fixed.asset.pojo.system.DictionaryEntity;
import com.sdkj.fixed.asset.pojo.system.DictionaryType;
import com.sdkj.fixed.asset.pojo.system.UsageManagement;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


/***
 *
 * @author scx
 *
 */
@Service
public class LoginService extends BaseService<UserManagement> {
    private static final Logger log = LoggerFactory.getLogger(LoginService.class);
    @Autowired
    private LoginMapper loginmapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public BaseMapper getMapper() {

        return loginmapper;
    }
    /**
     * 校验登录用户
     * @param tel
     * @param password
     * @return
     */
    public boolean isLegality(String tel,String password,boolean isPc){
        UserManagement user = getUserByTel(tel,isPc);
        if(null == user){
            throw new LogicException("用户不存在");
        }
        //判断公司是否禁用
        if(redisUtil.get("orgInfo")!= null && ((Map<String,Integer>)redisUtil.get("orgInfo")).get(user.getCompanyId()) != null && ((Map<String,Integer>)redisUtil.get("orgInfo")).get(user.getCompanyId()) == 2){
            throw new LogicException("公司已被禁用");
        }
        if(user.getPassword().equals(password)){
            return true;
        }
        return false;
    }


    /**
     * 通过电话号码获取登录用户
     * @param tel
     * @return
     */
    public UserManagement getUserByTel(String tel,boolean isPC){
        Example example = new Example(UserManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("tel",tel.trim());
        if(isPC){
            criteria.andEqualTo("type",1);
        }
        criteria.andNotEqualTo("state",2);
        List<UserManagement> userList = loginmapper.selectByExample(example);
        if(userList.size() == 0){
            return null;
        }
        if(userList.size() > 1){
            throw new LogicException("用户异常，同一账户存在多个");
        }
        if(userList.get(0).getState() == 3){
            throw new LogicException("用户已禁用");
        }
        return userList.get(0);
    }


    /**
     * 获取公司信息
     * @return
     */
    public Map<String,Object> getCompanyInfoForHomePage(String userId, Boolean isAdmin) {
        //获取公司信息
        List<CompanyBaseListResult> companyListResults = null;
        Map<String,Object> company = new HashMap<>();
        //判断是否是超管
        if(isAdmin){
            //如果是超级管理员
            companyListResults = loginmapper.getAllCompanys();
            company.put("belongToCompany","NONE");
        }else{
            //获取园区信息
            companyListResults = loginmapper.getUserCompany(userId);
            if(companyListResults.size() == 0){
                throw new LogicException("用户信息错误，无所属公司");
            }
            company.put("belongToCompany",companyListResults.get(0).getCompanyId());
           if(!companyListResults.get(0).getParentId().equals("NONE")){
                //查根节点
               companyListResults = loginmapper.getUserRootCompany(companyListResults.get(0).getParentId());
           }

        }
        company.put("companyId",companyListResults);

        return company;
    }
    /**
     * 获取角色信息
     * @param userId
     * @return
     */
    public List<LoginRole> getRoles(String userId){
        List<LoginRole> roles = loginmapper.getUserRoles(userId);
        return roles;
    }

    /**
     * 查询菜单
     * @return
     */
    public List<MenuResultEntity> getMenus() throws Exception {

        String token = request.getHeader("token");
        List<String> roleIds = cacheUtil.getUserRole(token);
        //如果是超管查询所有
        if (roleIds.contains(RoleType.SYSADMIN.getRoleType())) {
            return loginmapper.getAllMenus();
        } else {
            if (roleIds == null || roleIds.size() == 0) {
                return new ArrayList<>();
            }
            List<MenuResultEntity> authMenus = loginmapper.getAuthMenus(cacheUtil.getUserRoleId(token));
            Set<String> parentIds = new LinkedHashSet<>();
            //查询父节点是否包含在内
            for (MenuResultEntity menu : authMenus) {
                String allParentId = loginmapper.getAllParentId(menu.getAuthId());
                if (StrUtil.isNotBlank(allParentId)) {
                    for (String str : allParentId.split(",")) {
                        parentIds.add(str);
                    }
                }

            }


            Set<String> ids = authMenus.stream().map(MenuResultEntity::getAuthId).collect(Collectors.toSet());
            parentIds.removeAll(ids);
            //查询父机构信息
            if (parentIds.size() > 0) {
                List<MenuResultEntity> menusByMenuId = loginmapper.getMenusByMenuId(parentIds);
                authMenus.addAll(menusByMenuId);
            }

            Comparator<MenuResultEntity> netTypeComparator = new Comparator<MenuResultEntity>() {
                @Override
                public int compare(MenuResultEntity o1, MenuResultEntity o2) {
                    if (o1.getSort() == null) {
                        o1.setSort(1);
                    }
                    if (o2.getSort() == null) {
                        o2.setSort(1);
                    }
                    if (o1.getSort() > o2.getSort()) {
                        return 1;
                    }
                    if (o1.getSort().equals(o2.getSort())) {
                        return 0;
                    }
                    return -1;
                }
            };

            Collections.sort(authMenus, netTypeComparator);
            return authMenus;
        }

    }
    public boolean dicInCache() throws Exception {
        //查询所有数据字典
        List<DictionaryEntity> allDicEntity = loginmapper.getAllDicEntity();
        List<DictionaryType> dictionaryTypes = loginmapper.dicInCache();
        for(DictionaryEntity dic : allDicEntity){
            List<DictionaryResult> dicList = new ArrayList<>();
            for (DictionaryType type : dictionaryTypes){
                if(dic.getId().equals(type.getSdeId())){
                    DictionaryResult dicCache = new DictionaryResult();
                    dicCache.setSort(Integer.parseInt(type.getSort()));
                    dicCache.setName(type.getName());
                    dicCache.setValue(type.getValue());
                    dicList.add(dicCache);
                }
            }
          if(!redisUtil.hset("dic",dic.getCode(),dicList)){
              log.error("数据字典存储缓冲错误");
              return  false;
          }
        }
        return  true;
    }

    /**
     * 获取公司使用情况
     * @param companyId
     * @return
     */
    public UsageManagement getUsage(String companyId){
        return loginmapper.getUsage(companyId);
    }

}
